﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Ast.Framework.Events;
using Autofac.Builder;
using Autofac.Core;

namespace Ast.Framework.Forms
{
    public class FormEventHandlerRegistrationSource : IRegistrationSource
    {
        public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
        {
            var keyedService = service as KeyedService;
            if (keyedService == null || !typeof (IEnumerable<IEventHandler>).IsAssignableFrom(keyedService.ServiceType)) yield break;

            var componentRegistrations = registrationAccessor(new TypedService(typeof (Form)));
            foreach (var componentRegistration in componentRegistrations)
            {
                var interfaceType = componentRegistration.Activator.LimitType.GetInterface(keyedService.ServiceKey as string); // the form type must be an event handler
                if (interfaceType != null)
                {
                    // using created forms from Application.OpenForms as event handlers
                    yield return RegistrationBuilder.ForDelegate((context, parameters) => Application.OpenForms.Cast<Form>().Where(interfaceType.IsInstanceOfType).Cast<IEventHandler>())
                        .As(service)
                        .CreateRegistration();
                }
            }
        }

        public bool IsAdapterForIndividualComponents
        {
            get { return false; }
        }
    }
}